﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Century.Model;
using System.Web.Security;
using WebMatrix.WebData;

namespace Century.Web.Security.Authorizations
{
    public class CenturyAuthorization
    {

        public static bool Authorize(ActionModule actionModule)
        {
            using (CenturyDbContext db = new CenturyDbContext())
            {
                bool changeDbFlag = false;
                //Century.Model.User user = db.Users.Include("Roles.ActionModules").FirstOrDefault(c => c.UserName == userName);
                try
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        return false;
                    }

                    //var user = WebMatrix.WebData.WebSecurity.IsAuthenticated Membership.GetUser();
                    if (!WebSecurity.IsAuthenticated)
                    {
                        //user = new Century.Model.User { UserName = userName };
                        //db.Users.Add(user);
                        //changeDbFlag = true;
                        return false;
                    }
                    else if (Roles.IsUserInRole("Administrator"))
                    {
                        //user is admin so can se every where
                        return true;
                    }

                    ActionModule module = db.ActionModules.Include("ActionModuleRoles").FirstOrDefault(c => c.Name == actionModule.Name);
                    if (module == null)
                    {
                        module = new Century.Model.ActionModule { Name = actionModule.Name, DisplayName = actionModule.DisplayName, Group = actionModule.Group };
                        db.ActionModules.Add(module);
                        changeDbFlag = true;
                    }
                    else if (module.RequiredAdministrator)
                    {
                        //Resource needs admin permission and user is not admin.
                        return false;
                    }

                    if (changeDbFlag)
                    {
                        db.SaveChanges();
                    }
                    if (module.ActionModuleRoles == null)
                    {
                        return false;
                    }
                    foreach (var role in actionModule.ActionModuleRoles)
                    {
                        if (Roles.IsUserInRole(role.RoleName))
                        {
                            return true;
                        }
                    }
                    return false;
                }
                catch (Exception exc)
                {
                    return false;
                }
            }


        }
    }
}